#include <filetransffersystem.h>

#include <session.h>

void FileTransfferSystem::init() {
	threadCnt_ = std::thread::hardware_concurrency();
	for (int i = 0; i < threadCnt_; ++i) {
		std::shared_ptr<FileTransfferWork> worker = std::make_shared<FileTransfferWork>();
		fileTransfferWorks_.push_back(worker);
		worker->start();
	}
}

void FileTransfferSystem::postTask(std::shared_ptr<LogicNode> logicNode)
{
	std::hash<std::string> strHash;
	int idx = strHash(logicNode->session_->getId())%threadCnt_;
	std::lock_guard<std::mutex> locker(workLock_);
	if (idx > this->fileTransfferWorks_.size()) {
		throw std::runtime_error("postTask get fileTransffer thread idx out of range: " + std::to_string(idx));
	}
	fileTransfferWorks_[idx]->postTask(logicNode);
}

void FileTransfferSystem::stop() {
	for (int i = 0; i < threadCnt_; ++i) {
		auto worker = fileTransfferWorks_[i];
		worker->stop();
		worker.reset();
	}
}